package com.twobu.twobuinsight.controller;

import com.twobu.twobuinsight.common.Result;
import com.twobu.twobuinsight.dto.LoginRequest;
import com.twobu.twobuinsight.dto.LoginResponse;
import com.twobu.twobuinsight.dto.UserInfoResponse;
import com.twobu.twobuinsight.security.UserContext;
import com.twobu.twobuinsight.security.UserContextHolder;
import com.twobu.twobuinsight.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
@Tag(name = "认证管理", description = "认证相关接口")
@Deprecated
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 登录接口
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<LoginResponse> login(@RequestBody @Valid LoginRequest loginRequest, HttpServletRequest request) {
        // 调用登录服务
        LoginResponse loginResponse = authService.login(loginRequest);

        // 将token存入session
        HttpSession session = request.getSession(true);
        session.setAttribute("token", loginResponse.getToken());

        // 创建用户上下文并存入session
        UserContext userContext = new UserContext();
        userContext.setUserId(loginResponse.getUserId());
        userContext.setUsername(loginResponse.getUsername());
        userContext.setRoleId(loginResponse.getRoleId());
        userContext.setTenantId(loginResponse.getTenantId());
        session.setAttribute("userContext", userContext);

        // 设置session过期时间
        session.setMaxInactiveInterval(7200); // 2小时

        return Result.success(loginResponse);
    }

    /**
     * 退出登录接口
     */
    @PostMapping("/logout")
    @Operation(summary = "用户退出登录")
    public Result<Void> logout(HttpServletRequest request) {
        // 从session中获取token
        HttpSession session = request.getSession(false);
        if (session != null) {
            String token = (String) session.getAttribute("token");
            if (token != null) {
                // 调用登出服务
                authService.logout(token);
            }

            // 清除session
            session.invalidate();
        }

        // 清除ThreadLocal中的用户信息
        UserContextHolder.clear();

        return Result.success(null);
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    @Operation(summary = "获取当前登录用户信息")
    public Result<UserInfoResponse> getCurrentUser() {
        // 获取当前登录用户上下文
        UserContext userContext = UserContextHolder.getUserContext();
        if (userContext == null) {
            return Result.error("用户未登录");
        }

        // 根据userId查询用户详细信息
        UserInfoResponse userInfo = authService.getCurrentUserInfo(userContext.getUserId());

        return Result.success(userInfo);
    }

    /**
     * 刷新token
     */
    @PostMapping("/refresh")
    @Operation(summary = "刷新token")
    public Result<LoginResponse> refreshToken(HttpServletRequest request) {
        // 从session中获取token
        HttpSession session = request.getSession(false);
        if (session == null) {
            return Result.error("会话已过期，请重新登录");
        }

        String token = (String) session.getAttribute("token");
        if (token == null) {
            return Result.error("会话已过期，请重新登录");
        }

        // 调用刷新token服务
        LoginResponse loginResponse = authService.refreshToken(token);

        // 更新session中的token
        session.setAttribute("token", loginResponse.getToken());

        // 刷新session过期时间
        session.setMaxInactiveInterval(7200);

        return Result.success(loginResponse);
    }
}
